package com.sense.kukoo.biz_media.view

import android.os.Bundle
import android.text.Html
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.gson.Gson
import com.sense.feel.common.utils.ToastUtils
import com.sense.kukoo.biz_media.R
import com.sense.kukoo.biz_media.databinding.BizMediaActivityPodcastDetailBinding
import com.sense.kukoo.biz_media.vm.PodcastDetailViewModel
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.media.watcher.UserWatcher
import com.sense.kukoo.common.mvvm.view.BaseMvvmActivity
import com.sense.kukoo.common.repo.bean.BookBean
import com.sense.kukoo.common.repo.bean.BookDetailsBean
import com.sense.kukoo.common.repo.bean.BookItemBean
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.lib_logger.LoggerManager
import com.sense.kukoo.lib_picture.config.GlideConfig
import com.sense.kukoo.lib_picture.loader.Monet

@Route(path = ARouterUrl.ROUTE_MEDIA_MODULE_PODCAST_DETAIL_ACTIVITY)
class PodcastDetailActivity : BaseMvvmActivity<PodcastDetailViewModel, BizMediaActivityPodcastDetailBinding>() {

    private val TAG: String = javaClass.simpleName

    @JvmField
    @Autowired(name = ARouterUrl.KEY_FROM)
    var from: Int = -1 //1首页 2播客详情页 3播放列表

    @JvmField
    @Autowired(name = ARouterUrl.KEY_LOCAL_MEDIA_LIST_ITEMBEAN)
    var mLocalMediaListItemBean   : LocalMediaListItemBean? = null

    private var mCurrentMusic: LocalMediaListItemBean? = null
    private var mCurrentState: Int = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING

    override fun getLayoutId(): Int = R.layout.biz_media_activity_podcast_detail

    override fun getViewModelClass(): Class<PodcastDetailViewModel> = PodcastDetailViewModel::class.java

    override fun responseVM(action: Int) {}

    override fun initData() {
        ARouter.getInstance().inject(this)
        //
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        //
        LoggerManager.d(TAG,"from=${from}")
        LoggerManager.json(TAG, Gson().toJson(mLocalMediaListItemBean))
        //
        bindAction(mViewModel.action_back){
            finish()
        }
        //
        bindAction(mViewModel.action_share){
            val alias : String = mLocalMediaListItemBean?.titleOfChapter().toString()
            val type : Int = /*mLocalMediaListItemBean?.type ?:*/ -1
            val subTitle : String = mLocalMediaListItemBean?.titleOfChapter().toString()
            val author : String = mLocalMediaListItemBean?.authorOfBook().toString()
            val bookUrl : String = mLocalMediaListItemBean?.getAudioUrl().toString()
            val imgUrl : String = mLocalMediaListItemBean?.coverOfChapter().toString()
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_SHARE_MODULE_SHARE_ACTIVITY)
                .withString(ARouterUrl.KEY_SHARE_BOOK_TITLE, alias)
                .withInt(ARouterUrl.KEY_SHARE_BOOK_TYPE, type)
                .withString(ARouterUrl.KEY_SHARE_BOOK_SUB_TITLE, subTitle)
                .withString(ARouterUrl.KEY_SHARE_BOOK_AUTHOR, author)
                .withString(ARouterUrl.KEY_SHARE_BOOK_URL, bookUrl)
                .withString(ARouterUrl.KEY_SHARE_BOOK_IMAGE_URL, imgUrl)
                .navigation()
        }
        bindAction(mViewModel.action_download){}
        //
        mBinding.ivBtnPlay.setOnClickListener {
            //
            if(mLocalMediaListItemBean?.idOfChapter() ==  mCurrentMusic?.idOfChapter()){
                //相同的音乐
                when (mCurrentState) {
                    UserWatcher.MusicStateWatcher.STATE_SEEKING,
                    UserWatcher.MusicStateWatcher.STATE_PLAYING -> {
                        Kukoo.input.pause()
                    }
                    else -> {
                        Kukoo.input.start()
                    }
                }
            }else{
                playMusic()
            }
        }
        mBinding.tvMusicCollection.setOnClickListener {
            //to Collection
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_LIST_DETAIL_ACTIVITY)
                .withString(ARouterUrl.KEY_BOOK_ID_STR, ""+mLocalMediaListItemBean?.idOfBooks())
                .navigation()
        }
        //
        bindData(mViewModel.data_bookitem){ bookItem ->
            mBinding.slContent.visibility = View.VISIBLE
            //
            if(false){
                //使用接口查询的数据
                val url = bookItem.coverUrl ?: ""
                val title = bookItem.name ?: ""
                val collection = mLocalMediaListItemBean?.titleOfBooks() ?: ""
                val time = calculateTime(bookItem.duration ?: 0)
                val listens = "" + (bookItem.listeners ?: 0)
                val like = "" + (bookItem.likes ?: 0)
                val detail = bookItem.introduction ?: ""
                //
                Monet.get(ApplicationContext.instance())
                    .load<GlideConfig>(url)
                    .placeholder(com.sense.kukoo.common.R.mipmap.common_icon_default_editor_picks)
                    .into(mBinding.ivMusicIcon)
                mBinding.tvTitle.text = title
                mBinding.tvMusicCollection.text = collection
                mBinding.tvTime.text = time
                mBinding.tvListens.text = listens
                mBinding.tvLike.text = like
                mBinding.tvMusicDetail.setText(Html.fromHtml(detail))
            } else {
                /*//使用打开页面，传过来的数据
                val url = mLocalMediaListItemBean?.coverOfChapter() ?: ""
                val title = mLocalMediaListItemBean?.titleOfChapter() ?: ""
                val collection = mLocalMediaListItemBean?.titleOfBooks() ?: ""
                val time = calculateTime(mLocalMediaListItemBean?.book?.duration ?: 0)
                val listens = "" + (mLocalMediaListItemBean?.book?.listeners ?: 0)
                val like = "" + (mLocalMediaListItemBean?.book?.likes ?: 0)
                val detail = mLocalMediaListItemBean?.book?.introduction ?: ""
                //
                Monet.get(ApplicationContext.instance())
                    .load<GlideConfig>(url)
                    .placeholder(com.sense.kukoo.common.R.mipmap.common_icon_default_editor_picks)
                    .into(mBinding.ivMusicIcon)
                mBinding.tvTitle.text = title
                mBinding.tvMusicCollection.text = collection
                mBinding.tvTime.text = time
                mBinding.tvListens.text = listens
                mBinding.tvLike.text = like
                mBinding.tvMusicDetail.setText(Html.fromHtml(detail))*/
            }
        }
    }

    override fun initView() {
        val bookid = mLocalMediaListItemBean?.idOfBooks() ?: 0
        val chapter = /*mLocalMediaListItemBean?.book?.indexOfChapter() ?:*/ 0
        mViewModel.loadData(bookid, chapter)
    }

    private fun playMusic(){
        Kukoo.input.play(mLocalMediaListItemBean!!)
    }

    private fun refreshPlayBtnState(){
        if(mLocalMediaListItemBean?.idOfChapter() ==  mCurrentMusic?.idOfChapter()){
            //相同的音乐
            when (mCurrentState) {
                UserWatcher.MusicStateWatcher.STATE_PREPARE,
                UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                UserWatcher.MusicStateWatcher.STATE_SEEKING,
                UserWatcher.MusicStateWatcher.STATE_PLAYING -> {
                    mBinding.ivBtnPlay.setImageResource(com.sense.kukoo.common.R.drawable.common_icon2_pause_red_48dp)
                }
                else -> {
                    mBinding.ivBtnPlay.setImageResource(com.sense.kukoo.common.R.drawable.common_icon2_play_red_48dp)
                }
            }
        }else{
            mBinding.ivBtnPlay.setImageResource(com.sense.kukoo.common.R.drawable.common_icon2_play_red_48dp)
        }
    }

    private val mWatcher = object : UserWatcher.MusicStateWatcher{
        override fun onMusicChanged(music: LocalMediaListItemBean) {
            mCurrentMusic = music
            refreshPlayBtnState()
        }

        override fun onPlayTimeChanged(currentInt: Int, totalInt: Int, current: String, total: String) {}

        override fun onPlayPercentChanged(percent: Int) {}

        override fun onPlayStateChanged(state: Int) {
            mCurrentState = state
            refreshPlayBtnState()
        }

        override fun onPlaySpeedChanged(speed: Float) {}

        override fun onPlayListChanged() {}
    }

    private fun calculateTime(time: Int): String {
        return if (time >= 60) {
            val minute = time / 60
            val second = time % 60
            (if (minute < 10) "0$minute" else "" + minute) + if (second < 10) ":0$second" else ":$second"
        } else {
            if (time < 10) "00:0$time" else "00:$time"
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Kukoo.watcher.register(mWatcher)
    }

    override fun onDestroy() {
        super.onDestroy()
        Kukoo.watcher.unregister(mWatcher)
    }
}